package com.qty.apkviewer.worker

import android.content.Context
import android.content.Intent
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.qty.apkviewer.model.ApkInfo

class QueryAllPackagesWorker(public val context: Context, parameters: WorkerParameters): Worker(context, parameters){
    override fun doWork(): Result {
        val packageInfos = context.packageManager.getInstalledPackages(0)
        apks.clear()
        for (info in packageInfos) {
            val version = info.versionName
            info.providers
            val name = info.applicationInfo.loadLabel(context.packageManager).toString()
            val mainClassName = getMainClassName(context, info.packageName)
            val icon = info.applicationInfo.loadIcon(context.packageManager)
            val apkInfo = ApkInfo(version, name, info.packageName, mainClassName, icon)
            // QLog.d(this, "doWork=>apkinfo: ${apkInfo}")
            apks.add(apkInfo)
        }
        // QLog.d(this, "doWork=>package size: ${packageInfos.size}")
        return Result.success()
    }

    private fun getMainClassName(context: Context, packageName: String): String {
        val intent = Intent(Intent.ACTION_MAIN)
        intent.`package` = packageName
        intent.addCategory(Intent.CATEGORY_LAUNCHER)
        val activities = context.packageManager.queryIntentActivities(intent, 0)
        // QLog.d(this, "getMainClassName=>activities size: ${activities.size}")
        var mainClassName = ""
        if (activities.size > 0) {
            mainClassName = activities.get(0).activityInfo.name
        }
        return mainClassName
    }

    companion object {
        val apks = ArrayList<ApkInfo>()
    }
}